package cn.king.org.service.impl;

import cn.king.basic.service.impl.BaseServiceImpl;
import cn.king.org.domain.Department;
import cn.king.org.mapper.DepartmentMapper;
import cn.king.org.service.DepartmentServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DepartmentServiceImpl实现类
 */
@Service /** 1.将当前类交给Spring管理 2.实例化对象注解 3.创建对象的疏解；前提：扫描包路径 */
/** 支持当前事务，如果没有当前事务，就以非事务方法执行。 */
//@Transactional(readOnly = true,propagation = Propagation.SUPPORTS) 事务可以继承，直接抽取到公共类
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentServiceI {

    /**
     * @Autowired：注入：该当前属性赋值
     * 前提：Spring容器中必须有给类型或子类型的对象
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    /** 查询部门树 */
    @Override
    public List<Department> deptTree() {
        //获取到所有的部门
        List<Department> departments = departmentMapper.getAll();
        //将所有的部门信息保存在map中，方便根据id去获取部门信息，就不用查数据库了
        Map<Long,Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        //遍历所有的部门，如果是顶级部门[parent_id==null],加到部门树
        for (Department department : departments) {
            if (department.getParent_id() == null){
                deptTree.add(department);
            }else {
                //如果不是顶级部门[parent_id!=null],找到自己的父部门，将自己加到父部门的children
                //获取父部门的id - 获取父部门对象 - 获取父部门的children集合
                Long parentId = department.getParent_id();
                //根据id获取父部门
                Department parentdept = map.get(parentId);
                //防止父部门的数据删除引起的空指针异常
                if (parentdept != null){
                    parentdept.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
